package com.demo.core.service.base.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.CollectionUtils;

import com.demo.core.dao.AreaDao;
import com.demo.core.dao.base.support.ResultSearchResult;
import com.demo.core.dao.base.support.SearchArgumentSupport;
import com.demo.core.model.Area;
import com.demo.core.model.support.converter.AdjacencyListToChainedObjectConverter;
import com.demo.core.service.base.AreaService;

public class AreaServiceImpl implements AreaService {

	/**
	 * 区域数据访问层接口
	 */
	private AreaDao areaDao;
	
	@Override
	public Long save(Area t) {
		return areaDao.insert(t);
	}

	@Override
	public boolean exists(Long id) {
		return areaDao.exists(id);
	}

	@Override
	public void delete(Long id) {
		areaDao.delete(id);
	}

	@Override
	public void update(Long id, String name, String code) {
		Map<String, Object> params = new HashMap<String, Object>(3);
		params.put("id", id);
		Area area = new Area();
		area.setCode(code);
		area.setName(name);
		areaDao.update(area, params);
	}

	@Override
	public Area find(Long id) {
		return areaDao.select(id);
	}

	@Override
	public Area find(Long siteId, String code) {
		Map<String, Object> params = new HashMap<String, Object>(5);
		params.put("siteId", siteId);
		params.put("code", code);
		List<Area> areaList = areaDao.select(params); 
		return (areaList == null || areaList.size() == 0) ? null : areaList.get(0);
	}

	@Override
	public List<Area> findList(Long siteId) {
		Map<String, Object> params = new HashMap<String, Object>(3);
		params.put("siteId", siteId);
		return areaDao.select(params); 
	}

	@Override
	public Area tree(Long id, int... depths) {
		Map<String, Object> params = new HashMap<String, Object>(3);
		params.put("id", id);
		if (depths != null && depths.length > 0) {
			List<?> depthList = CollectionUtils.arrayToList(depths);
			params.put("depthList", depthList);
		}
		List<Area> areaList = areaDao.tree(params);
		
		return AdjacencyListToChainedObjectConverter.conver(areaList);
	}

	@Override
	public Area tree(Long id) {
		return tree(id);
	}

	@Override
	public ResultSearchResult<Area> search(Long siteId, int firstResult, int maxResults) {
		if (firstResult < 0 || maxResults < 1) {
			return null;
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("siteId", siteId);

		return areaDao.search(params, new SearchArgumentSupport(firstResult, maxResults));
	}

	public void setAreaDao(AreaDao areaDao) {
		this.areaDao = areaDao;
	}
}
